// admissAdd.js
var app = getApp();
var utils=require('../../utils/util.js');

function fadeOut(that){
  var fadeOutTimeout = setTimeout(function(){
    that.setData({
      tips: ""
    });
    clearTimeout(fadeOutTimeout)
  },1000)
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    courses:["钢琴班","奥数班","体育班","艺术班"],
    relationship:["母子","母女", "父子", "父女"],
    sex: ["男", "女"],
    grade: [],
    gradeList:[],
    gradeId:0,
    course: [],
    courseList:[],
    courseId: '',
    indexCourse: 0,
    indexSex: 0,
    indexGrade: 0,
    indexRelationship: 0,
    tips:"",
    phoneFlag: true,
    parentPhoneFlag: true,
    id: 0,
    optionsId: "",
    studentId:0,
    studentName : "",
    studentPhone : "",
    studentNo : "",
    school : "",
    gradeName: "",
    address : "",
    email : "",
    studentAnalysis : "",
    className: "",
    parents: [
      {
        id:"",
        parentName : "",
        parentCall :"",
        phone : ""
      }
    ],
    parentsId:0,
    analysis :[],
    onceIntention :"0",
    nowIntention :"1",
   
  },

  addParent: function(e){
    var parents = this.data.parents;
    console.log("addParent===",e);
    parents.push({
        parentName : "",
        parentCall : "",
        phone: ""
      });
    this.setData({
      parents: parents
    })
  },

  // 课程改变
  courseChange: function(e){
    var that = this;
    var courseList = that.data.courseList
    var course =that.data.course
    var courseId = that.data.courseId
    console.log(courseList)
    console.log(course)
    console.log("意向课程==课程改变==的输出值为：", e.detail.value);
    console.log("年级id为", course[e.detail.value].id)
     that.setData({
       indexCourse: e.detail.value,
       courseId: course[e.detail.value].id
     });
     console.log(that.data.courseId)
  },
// 性别改变
 sexChange: function(e){
   var that = this;
    console.log("意向课程的输出值为：", e);
    that.setData({
      indexSex: e.detail.value
    });
  },
//年级改变
 gradeChange: function(e){
   var that = this;
   var gradeList = that.data.gradeList
   var grade =that.data.grade
   var gradeId = that.data.gradeId
   console.log(gradeList)
   console.log(grade)
   console.log("意向课程==年级改变==的输出值为：", e.detail.value);
   console.log("年级id为", grade[e.detail.value].id)
    that.setData({
      indexGrade: e.detail.value,
      gradeId: grade[e.detail.value].id
    });
    console.log(that.data.gradeId)
  },

  //保存家长名称
  // parentName: function(e){
  //   var that = this;
  //   console.log("====",e);
  //   var index = e.currentTarget.dataset.index;
  //   that.data.parents[index].parentName  = e.detail.value;
  //   that.setData({
  //     parents: that.data.parents
  //   })
  // },
  //保存家长关系
  // parentRelation: function(e){
  //   var that = this;
  //   console.log("====",e);
  //   var index = e.currentTarget.dataset.index;
  //   that.data.parents[index].parentCall  = e.detail.value;
  //   that.setData({
  //     parents: that.data.parents
  //   })
  // },
 
  //家长验证手机号码
  checkPhone: function(e){
    console.log("检查手机号码的输出值为：", e);
    var that = this;
    var tips = that.data.tips;
    var index = e.target.dataset.index;
    var value = e.detail.value;
    var phoneFlag = that.data.phoneFlag;
    var reg = /^1(3|4|5|7|8)\d{9}$/;
    if(value && !(reg.test(value))){
      that.setData({
        tips: "请填写正确的手机号码",
        phoneFlag: false
      });
      fadeOut(that);
      return
    }else{
      that.setData({
        phoneFlag : true
      })
    }
  },
 //保存家长手机号
  // parentPhone: function(e){
  //   var that = this;
  //   console.log("====",e);
  //   var index = e.currentTarget.dataset.index;
  //   var phoneFlag = that.data.phoneFlag;
  //   that.data.parents[index].phone = e.detail.value;
  //   if(phoneFlag == true){
  //     that.setData({
  //       parent: that.data.parent
  //     })
  //   }
  // },


  // 保存按钮
  formSubmit:function(e){
    var that = this;
    var detail = e.detail.value;

    //parent数组
    var List = [];
    for(const i in detail){
      if (i.indexOf("parentName") > -1){
        if (!List[i.split("parentName")[1]]) List[i.split("parentName")[1]]={}
        List[i.split("parentName")[1]]["parentName"] = detail[i];
      } else if (i.indexOf("phone") > -1){
        if (!List[i.split("phone")[1]]) List[i.split("phone")[1]] = {}
        List[i.split("phone")[1]]["phone"] = detail[i];
      } else if (i.indexOf("parentCall") > -1) {
        if (!List[i.split("parentCall")[1]]) List[i.split("parentCall")[1]] = {}
        List[i.split("parentCall")[1]]["parentCall"] = detail[i];
      }  
    };
    if (that.data.optionsId) {
      List[0]["id"] = this.data.parentsId
    }

    //手机号码数组
    var phoneList = [];
    for (const i in detail) {
      if (i.indexOf("phone") > -1) {
        phoneList.push(detail[i]);
      }
    }
    //验证家长手机号码是否重复
    for (let i = 0; i < phoneList.length; i++) {
      for (let j = i + 1; j < phoneList.length; j++) {
        if (phoneList[i] == phoneList[j]) {
          that.setData({
            tips: "手机号码重复",
            parentPhoneFlag: false
          });
          fadeOut(that);
          return
        } else {
          that.setData({
            parentPhoneFlag: true
          });
        }
      }
    }
    console.log("phoneList===", phoneList);
    console.log("parent数组==",List)
    console.log('form发生了submit事件，携带数据为：', e.detail.value);
    console.log("that.data.grade====", that.data.gradeId);
    console.log("phoneFlag===", that.data.phoneFlag);
    var phoneFlag = that.data.phoneFlag;
    var parent = that.data.parents;
    var parentName = List[0].parentName;
    var parentRelation = List[0].parentCall;
    var parentPhone = List[0].phone;
    var emailReg = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

    if(detail.name == ""){
      that.setData({
        tips: "请填写姓名"
      })
      fadeOut(that);
      return;
    } else if (detail.studentPhone == ""){
      that.setData({
        tips: "请填写手机号码！"
      });
      fadeOut(that);
      return; 
    } else if (!(/^1(3|4|5|7|8)\d{9}$/.test(detail.studentPhone))){
      that.setData({
        tips: "手机号码格式不正确"
      });
      fadeOut(that);
      return; 
    }else if((detail.email)&&!(emailReg.test(detail.email))){
      that.setData({
        tips: "邮箱格式不正确"
      });
      fadeOut(that);
      return;
    }else if(parentName=="" || parentRelation=="" ||parentPhone=="" ){
      that.setData({
        tips: "请至少输入一个完整的家长信息"
      });
      fadeOut(that);
      return;
    }
    else if (phoneFlag && that.data.parentPhoneFlag){
      console.log("所有验证成功");
      console.log("studentName==",detail.name);
      console.log("studentPhone===", detail.studentPhone);
      console.log("school===",detail.school);
      console.log("email===",detail.email);
      console.log("sex===",detail.sex);
      console.log("parents===",List);
      console.log("gradeId===",that.data.gradeId);
      console.log("classId===", that.data.courseId);
      console.log("analysis===",that.data.analysis);
          wx.request({
            url: app.globalData.http + "selectOnlyParentPhone.do",
            header: {
              'content-type': 'application/json'
            },
            data: {
              busId: parseInt(wx.getStorageSync("busId")),
              employeesId: parseInt(wx.getStorageSync("employeesId")),
              schoolId: parseInt(wx.getStorageSync("schoolId"))
            },
            success: function(res){
              var code = res.data.code;
              console.log("验证手机号码唯一性的返回数据==",res.data);
              if(code == 100){
                wx.request({
                  url: app.globalData.http + "newStudent.do",
                  header: {
                    'content-type': 'application/json'
                  },
                  data: {
                    students : [
                      {
                        id: parseInt(that.data.optionsId),
                        studentName : detail.name,
                        studentPhone: detail.studentPhone,
                        headImage : "",
                        school : detail.school,
                        sex : detail.sex,
                        address : "",
                        email : detail.email,
                        studentAnalysis : "",
                        onceIntention : "0",
                        nowIntention : "1",
                        train : "",
                        gradeId : parseInt( that.data.gradeId),
                        classId: parseInt(that.data.courseId),
                        analysis: that.data.analysis ,
                      }
                    ],
                    parents: List,
                    busId: parseInt(wx.getStorageSync("busId")),
                    employeesId: parseInt(wx.getStorageSync("employeesId")),
                    schoolId: parseInt(wx.getStorageSync("schoolId"))
                  },
                  success:function(res){
                    console.log("新增意向学院成功返回数据：", res.data);
                    var code = res.data.code;
                    if(code == 100){
                        if(that.data.optionsId == ""){
                          wx.navigateTo({
                            url: "/pages/admissSuccess/admissSucess"
                          })
                        }else{
                          wx.redirectTo({
                            url: "/pages/admissGenSuccess/admissGenSuccess?id="+that.data.optionsId
                          })
                        } 
                    }
                    if(code == 300){
                      wx.showToast({
                        title: '提交失败',
                        image: "/img/ico/fail.png",
                        duration: 2000
                      });
                      return
                    }
                  }
                }) 
              }else if(code == 200){
                that.setData({
                  tips: "手机号码已经存在"
                });
                fadeOut(that);
                return;
              }
            }
          })
       
      
    }
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //console.log("options====", options);
    var that = this;

    //年级接口
    wx.request({
      url: app.globalData.http + "findGradeAllList.do",
      header: {
        'content-type': 'application/json'
      },
      data:{
        busId: parseInt(wx.getStorageSync("busId")),
        employeesId: parseInt(wx.getStorageSync("employeesId")),
        schoolId: parseInt(wx.getStorageSync("schoolId"))
      },
      success: function(res){
        console.log("年级=====",res.data);
        var code = res.data.code;
        var grade = that.data.grade;
        var gradeList = [];
        if(code == 100){
          var list = res.data.data;
          var indexGrade = that.data.indexGrade;
          for(var i = 0; i < list.length; i++){
            gradeList.push(list[i].gradeName);
          }
          that.setData({
            grade: list,
            gradeList: gradeList
          });
          var gradeId = that.data.grade[indexGrade].id;
          that.setData({
            gradeId:gradeId 
          })
        }
      },
      fail: function(e){
        console.log("接口异常")
      }
    });
    //课程接口
    wx.request({
      url: app.globalData.http + "findAllClassOption.do",
      header: {
        'content-type': 'application/json'
      }, 
      data:{
        busId: parseInt(wx.getStorageSync("busId")),
        employeesId: parseInt(wx.getStorageSync("employeesId")),
        schoolId: parseInt(wx.getStorageSync("schoolId"))
      },
      success: function(res){
        console.log("意向课程-====", res.data);
        var code = res.data.code;
        var course = that.data.course;
        var courseList = [];
        var indexCourse = that.data.indexCourse;
        if(code == 100){
          var list = res.data.data;
         
          for(var i = 0; i < list.length; i++){
            courseList.push(list[i].className );
          }
          that.setData({
            course: list,
            courseList: courseList
          });
          var courseId = that.data.course[indexCourse].id;
          that.setData({
            courseId: courseId 
          })
          console.log("course=====", that.data.course);
          console.log("courseList=====", that.data.courseList);
          console.log("indexCourse====", indexCourse)
          console.log("courseId=====", that.data.courseId)
        }
      }
    })

    //修改信息的时候请求
    if(options.id){
      wx.request({
        url: app.globalData.http + "fromStudent.do",
        header: {
          'content-type': 'application/json'
        },
        data:{
          studentId : parseInt(options.id),
          busId: parseInt(wx.getStorageSync("busId")),
          employeesId: parseInt(wx.getStorageSync("employeesId")),
          schoolId: parseInt(wx.getStorageSync("schoolId"))
        },
        success: function(res){
          var code = res.data.code;
          console.log("修改信息请求数据===",res.data)
          console.log("修改信息请求数据ID===", options.id)
          console.log("修改信息请求数据parentId===", res.data.data.parents[0].id)
          if(code == 100){
            that.setData({
              optionsId: options.id,
             'studentName':res.data.data.studentName,
             'studentPhone': res.data.data.studentPhone,
             //'studentNo': res.data.data.studentNo,
             'school': res.data.data.school,
             'gradeName': res.data.data.gradeName,
             'address': res.data.data.address,
             'email': res.data.data.email,
             'studentAnalysis': res.data.data.studentAnalysis,
             'parents': res.data.data.parents,
             'parentsId': res.data.data.parents[0].id,
             'analysis' :res.data.data.analysis,
             'className': res.data.data.className,
             'indexSex': res.data.data.sex,
             'onceIntention':res.data.data.onceIntention
            });
            var gradeList = that.data.gradeList;
            var gradeName = that.data.gradeName;
            var indexGrade = gradeList.indexOf(gradeName);
            var courseList = that.data.courseList;
            var courseName = that.data.className;
            var indexCourse = courseList.indexOf(courseName);
            console.log('gradeList========', gradeList);
            console.log('gradeName========', gradeName);
            console.log('indexGrade========', indexGrade);
            console.log('courseList========', courseList);
            console.log('courseName========', courseName);
            console.log('indexCourse========', indexCourse);
            for(var i in gradeList){
              if(gradeList[i] == gradeName){
                that.setData({
                  indexGrade: i
                })
              }
            }
            for (var i in courseList) {
              if (courseList[i] == courseName) {
                that.setData({
                  indexCourse: i
                })
              }
            }
            console.log("indexGrade==",that.data.indexGrade)
          }
        }
      })
    }
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})